<template>
  <div>
    登录中
  </div>
</template>

<script>
import {defineComponent} from 'vue'
import {ElLoading, ElMessage} from "element-plus";
import userStore from "@/store/UserStore";
import pinia from "@/store/pinia";
import loginStore from "@/store/loginStore";

const store = userStore(pinia);
const storeLogin = loginStore(pinia);

export default defineComponent({
  name: "callback",
  props: ['accountType'],
  data() {
    return {
      store, storeLogin
    }
  },
  created() {
    this.code = this.$route.query.code
    // console.log(this.accountType)
    // console.log(this.code)
    this.login()
  },
  methods: {
    async login() {
      // 全局加载
      const loadingInstance = ElLoading.service({text: "登录中，请稍后", lock: true})
      let {data: result} = await this.$http.get('/api/login/otherLogin', {
        params: {
          otherType: this.accountType,
          code: this.code
        }
      })
      if (result.dataMap.userInfo && result.dataMap.token){
        window.sessionStorage.setItem("userInfo", JSON.stringify(result.dataMap.userInfo))
        window.sessionStorage.setItem("token", JSON.stringify(result.dataMap.token))
      }
      // 如果code == 200，保存数据，转到index
      if (result.code === 200) {
        ElMessage.success({showClose: true, message: "登录成功！"})
        this.store.updateToken(result.dataMap.token)
        this.store.updateUserInfo(result.dataMap.userInfo)
        // console.log(this.store.userInfo)
        // 如果有页面跳转，跳转到指定页面，否则跳转到首页
        const nextPath = this.storeLogin.getNextPath
        loadingInstance.close()
        if (nextPath) {
          // 如果有name属性，跳转name
          if (nextPath.name) {
            this.storeLogin.setNextPath(null)
            this.$router.push({name: nextPath.name, params: nextPath.params})
          } else {
            // 否则跳转路径
            this.storeLogin.setNextPath(null)
            this.$router.push({path: nextPath.path, query: nextPath.query})
          }
        } else {
          this.$router.push({name: "index"})
        }
      } else {
        loadingInstance.close()
        // 如果code是其他，显示错误信息
        ElMessage.error(result.msg)
        this.$router.push({name: "index"})
      }
    }
  }
})
</script>

<style scoped>

</style>